package com.zhuhjay.service.imchat.handler;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.zhuhjay.common.base.annotation.ApiLimiter;
import com.zhuhjay.common.base.enums.LimiterEnums;
import com.zhuhjay.common.netty.handler.AbstractSocketHandler;
import com.zhuhjay.common.netty.handler.AuthParserHandler;
import com.zhuhjay.common.netty.handler.SocketLimiterHandler;
import com.zhuhjay.service.imchat.model.dto.ChatMessageDto;
import com.zhuhjay.service.imchat.model.entity.ChatRoom;
import com.zhuhjay.service.imchat.service.ChatMessageService;
import com.zhuhjay.service.imchat.service.ChatRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ZhuHJay
 * @date 2023/7/10 11:47
 */
@Slf4j
@Component
@ApiLimiter(limit = 6, expire = 10, strategy = LimiterEnums.USER, message = "发送消息过于频繁!")
public class MessageSocketHandler extends AbstractSocketHandler<ChatMessageDto> {

    public MessageSocketHandler(
            SocketIOServer socketServer, AuthParserHandler authParserHandler,
            SocketLimiterHandler socketLimiterHandler) {
        super(socketServer, authParserHandler, socketLimiterHandler);
        // 只需要进行Event事件监听
        socketServer.addEventListener(getEventName(), getDataType(), this);
    }

    @Resource
    private ChatMessageService chatMessageService;
    @Resource
    private ChatRoomService chatRoomService;

    @Override
    protected String getEventName() {
        return "message";
    }

    @Override
    protected Class<ChatMessageDto> getDataType() {
        return ChatMessageDto.class;
    }

    @Override
    protected void onEvent(SocketIOClient client, ChatMessageDto dto, AckRequest ackSender) {
        ChatRoom room = chatRoomService.getById(dto.getRoomId());
        if (room == null) {
            return;
        }
        // 进行消息处理
        chatMessageService.sendMessage(dto, getEventName());
    }

}
